function [F, ix] = h5_filter_dead (state, A, B, cols)

  %% usage:  F = h5_filter_dead (state, A, B, cols)
  %%
  %% Given a 'state' vector which has negative entries for bodies which
  %% should be ignored and a matrix or column vector 'A' which contains
  %% 'B' elements for each body, this function returns a matrix F such
  %% that all the rows corresponding to 'dead'  indices are removed.
  %%
  %% INPUTS:
  %% state:  a vector with non positive entries which must be filtered
  %% A    :  a matrix or column vector with B rows of data for each body
  %% B    :  the number of data for each bodies
  %% cols : put to 'cols' to filter columns or 'rows' for rows.  Default is rows. 
  %% 
  %% OUTPUTS:
  %% F    : the filtered matrix.
  %%
  
  live = find(state > 0);
  

  %% First we make a column vector with one entry per live body.
  %% This is multiplied by the stride, B, so the result is a vector
  %% whose entries point to the begining of the block corresponding to
  %% the live entries
  ix = B * (live-1);
  %% now, we build a matrix with B columns in which each row
  %% contains the indices of the rows in A which belong to the live
  %% block. 
  
  ix = diag(ix) * ones(size(live,1),B) + ones(size(live, 1), B) * diag((1:B));
  %% now unfoled this into a column vector. 
  ix = reshape(ix', numel(ix), 1);
 
  %% now filter out the unwanted elements in 
  if (exist(cols)  && strcmp(cols, 'cols'))
    F = A(:, ix); 		% better for sparse matrices
  elseif ( ( exist(cols) && strcmp(cols, 'rows')  ) || ~exist(cols) )
    F  = A(ix, :); 
  end

end
